package com.fast.controller.thread.factory;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

/**
 *
 */
@Configuration
public class ThreadPoolFactory {

	@Bean(destroyMethod = "shutdown")
	public ThreadPoolExecutor voidThreadPool() {
		return new ThreadPoolExecutor(
				Runtime.getRuntime().availableProcessors() * 2,
				Runtime.getRuntime().availableProcessors() * 2,
				60,
				TimeUnit.SECONDS,
				new ArrayBlockingQueue<>(300),
				ThreadFactoryBuilder.create().setNamePrefix("void_thread_pool_").build(),
				new ThreadPoolExecutor.AbortPolicy()
		);
	}

	@Bean(destroyMethod = "shutdown")
	public ThreadPoolExecutor resultThreadPool() {
		return new ThreadPoolExecutor(
				Runtime.getRuntime().availableProcessors() * 2,
				Runtime.getRuntime().availableProcessors() * 2,
				60,
				TimeUnit.SECONDS,
				new ArrayBlockingQueue<>(300),
				ThreadFactoryBuilder.create().setNamePrefix("result_thread_pool_").build(),
				new ThreadPoolExecutor.AbortPolicy()
		);
	}

	@Bean
	public <R> CompletionService<R> futureCompletionService(@Qualifier(value = "resultThreadPool") ThreadPoolExecutor threadPoolExecutor) {
		return new ExecutorCompletionService<>(threadPoolExecutor);
	}


	@Bean(destroyMethod = "shutdown")
	public ThreadPoolExecutor callBackOaThreadPool() {
		return new ThreadPoolExecutor(
			Runtime.getRuntime().availableProcessors() * 2,
			Runtime.getRuntime().availableProcessors() * 2,
			60,
			TimeUnit.SECONDS,
			new ArrayBlockingQueue<>(100),
//			new BasicThreadFactory.Builder().namingPattern("callao-thread-pool").build(),
				ThreadFactoryBuilder.create().setNamePrefix("callao-thread-pool").build(),
			new ThreadPoolExecutor.AbortPolicy()
		);
	}


}
